package com.tuanzi.loan.web.bean.xhh.settlementsystem;

import com.google.common.collect.Lists;
import com.tuanzi.loan.business.entity.xhh.settlementsystem.XhhSettlementIncome;
import com.tuanzi.loan.business.service.xhh.settlementsystem.XhhSettlementIncomeService;
import com.tuanzi.loan.business.service.xhh.settlementsystem.XhhSettlementProductService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.vo.request.xhh.settlementsystem.XhhSettlementProductRequest;
import com.tuanzi.loan.vo.response.xhh.settlementsystem.XhhSettlementProductResponse;
import com.tuanzi.loan.web.configuration.JSFListingBean;
import com.tuanzi.loan.web.lazy.xhh.settlementsystem.XhhSettlementProductLazyDataModel;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.bean.ViewScoped;
import java.util.List;

import static com.tuanzi.loan.business.constants.DictionaryCode.*;

/**
 * @author caiwanlin
 * @create 2018-08-16 20:30
 */
@Data
@Debug
@Component
@ViewScoped
@EqualsAndHashCode(callSuper = true)
public class XhhSettlementProductListBean extends JSFListingBean<XhhSettlementProductRequest, XhhSettlementProductResponse> {

    private static final String INFO_URL = "/views/xhh/settlementsystem/product-info.xhtml";

    @Autowired
    private XhhSettlementProductService xhhSettlementProductService;

    @Autowired
    private XhhSettlementIncomeService xhhSettlementIncomeService;

    @PostConstruct
    public void init() throws Exception {
        initLazyDataModel();
    }

    private void initLazyDataModel() throws Exception {
        XhhSettlementProductRequest request = (XhhSettlementProductRequest) getParam();
        $ = new XhhSettlementProductRequest();
        if (request != null) {
            $ = request;
        }
        lazyDataModel = new XhhSettlementProductLazyDataModel($);
    }

    public void onReset() throws Exception {
        initLazyDataModel();
    }

    public String onAdd() {
        return redirect(INFO_URL, $);
    }

    public String onSee(Long id) {
        return redirect(INFO_URL + "?id=" + id, $);
    }

    public void onDelete(Long id) {
        List<XhhSettlementIncome> settlementIncomes = xhhSettlementIncomeService.findAllByProductId(id);
        if (null != settlementIncomes && !settlementIncomes.isEmpty()) {
            addErrorMessage("有关联的消耗记录不能删除");
            return;
        }
        xhhSettlementProductService.onDelete(id);
        addSuccessfullyMessage();
    }

    @Override
    protected List<String> getDictionaryCodes() {
        return Lists.newArrayList(XHH_SETTLEMENT_INCOME_TYPE, XHH_COOPERATION_MODE, XHH_SETTLEMENT_CYCLE, XHH_SETTLEMENT_BILLING_PROJECT);
    }
}
